'use strict';
// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('Eamclient', ['ionic', 'config', 'Eamclient.controllers',
    'Eamclient.services', 'Eamclient.filters'
])

.run(function($ionicPlatform, $timeout, $rootScope, $state, $log, store, webq, ntm) {
    $ionicPlatform.ready(function() {

        // debuggy /#/tab/inspection/54c88386e6771300e14d6802
        // store.saveInspection({
        //     "id": "54c88386e6771300e14d6802",
        //     "author_id": "54c881b478ec9f6d38508a9b",
        //     "eam_wind_turbine_id": "sasa",
        //     "eam_component_id": "sasa",
        //     "eam_root_cause": "# ooo",
        //     "eam_alarm_level": 3,
        //     "eam_maintain_toolkits": [{
        //         "icon": "/public/dummy-data/toolkit.jpg",
        //         "footer": true,
        //         "count": "1",
        //         "name": "s1x"
        //     }],
        //     "eam_inspection_assignee": "mike001",
        //     "eam_wo_category": "inspection",
        //     "eam_repair_guide": "# bbb",
        //     "eam_maintain_parts": [{
        //         "icon": "/public/dummy-data/part.png",
        //         "footer": true,
        //         "count": "1",
        //         "name": "1xx"
        //     }],
        //     "eam_timestamp": "2015-01-28T06:36:54.778Z",
        //     "eam_wo_id": 101,
        //     "author": {
        //         "loginname": "mike001",
        //         "avatar_url": "//gravatar.com/avatar/1d4b69ca93d0e73e068427e37eed661b?size=48"
        //     }
        // });



        function _start(lng) {
                // init i18next
                window.i18n.init({
                    lng: lng, // If not given, i18n will detect the browser language.
                    fallbackLng: 'dev', // Default is dev, using Chineses for dev
                    useCookie: false,
                    useLocalStorage: false,
                    resGetPath: 'locales/__lng__/__ns__.json'
                }, function(tFunction) {
                    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                    // for form inputs)
                    window.t = tFunction;

                    if (window.cordova && window.cordova.plugins.Keyboard) {
                        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    }
                    if (window.StatusBar) {
                        // org.apache.cordova.statusbar required
                        StatusBar.overlaysWebView(true);
                        StatusBar.styleLightContent();
                        StatusBar.backgroundColorByName('white');
                        // StatusBar.hide();
                    }

                    // navigator.splashscreen.hide();
                    if (window.navigator.splashscreen) {
                        var credentail = store.getAccessToken();
                        if ((!ntm.getNetwork()) && credentail.access_token) {
                            // also bring user to dash tab
                            $state.go('tab.inspections');
                            $timeout(function() {
                                navigator.splashscreen.hide();
                            }, 1000);
                        } else if (credentail.access_token) {
                            webq.getMyProfile()
                                .then(function() {
                                    $state.go('tab.inspections');
                                    $timeout(function() {
                                        navigator.splashscreen.hide();
                                    }, 1000);
                                }, function() {
                                    $state.go('login-form');
                                    $timeout(function() {
                                        navigator.splashscreen.hide();
                                    }, 1000);
                                })
                        } else {
                            $state.go('login-form');
                            $timeout(function() {
                                navigator.splashscreen.hide();
                            }, 1000);
                        }
                    }
                });
            }
            // debuggy
            // _start();

        /**
         * comment out for grunt serve
         */
        navigator.globalization.getPreferredLanguage(
            function(language) {
                $log.warn('language: ' + JSON.stringify(language));
                if (_.indexOf(['en', 'en-US'], language.value) == -1) {
                    _start('dev');
                } else {
                    _start('en-US');
                }
            },
            function() {
                $log.error('Error getting language\n');
                // set default locale as Chinese
                _start('dev');
            }
        );

    });
})

.config(function($stateProvider, $urlRouterProvider) {

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js
    $stateProvider

    // setup an abstract state for the tabs directive
        .state('tab', {
        url: '/tab',
        abstract: true,
        templateUrl: 'templates/tabs.html',
        //  https://github.com/driftyco/ng-cordova/issues/8
        //  use the resolve feature of the UI router to wait 
        //  for ionic.Platform.ready signal before each state 
        //  that might need a plugin
        resolve: {
            cordova: function($q, $log) {
                var deferred = $q.defer();
                ionic.Platform.ready(function() {
                    $log.debug('ionic.Platform.ready');
                    deferred.resolve();
                });
                return deferred.promise;
            }
        }
    })

    // Each tab has its own nav history stack:

    .state('tab.inspections', {
        url: '/inspections',
        views: {
            'tab-inspections': {
                templateUrl: 'templates/tab-inspections.html',
                controller: 'InspectionsCtrl'
            }
        }
    })

    .state('tab.inspection', {
        url: '/inspection/:id',
        views: {
            'tab-inspections': {
                templateUrl: 'templates/inspection.html',
                controller: 'InspectionCtrl'
            }
        }
    })

    .state('tab.maintenances', {
        url: '/maintenances',
        views: {
            'tab-maintenances': {
                templateUrl: 'templates/tab-maintenances.html',
                controller: 'MaintenancesCtrl'
            }
        }
    })

    .state('tab.maintenance', {
        url: '/maintenance/:id',
        views: {
            'tab-maintenances': {
                templateUrl: 'templates/maintenance.html',
                controller: 'MaintenanceCtrl'
            }
        }
    })

    .state('tab.account', {
        url: '/account',
        views: {
            'tab-account': {
                templateUrl: 'templates/tab-account.html',
                controller: 'AccountCtrl'
            }
        }
    })

    .state('login-form', {
        url: '/login-form',
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl',
        resolve: {
            cordova: function($q) {
                var deferred = $q.defer();
                ionic.Platform.ready(function() {
                    deferred.resolve();
                });
                return deferred.promise;
            }
        }

    });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/inspections');

});
